package com.ai.spring.common.util;

import com.ai.spring.common.enums.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.io.Serializable;
import java.util.Set;

/**
 * 验证工具类
 *
 * @author 石头
 * @Date 2019/11/20
 * @Version 1.0
 **/
@Slf4j
public class ValidationUtils {
    /**Validation factory 单例*/
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    public static <T,M extends Serializable> ResponseResult<M> validateEntity(T obj,Class<?> ...groups) {
        Set<ConstraintViolation<T>> set = validator.validate(obj, groups);
        if (!CollectionUtils.isEmpty(set)){
            for (ConstraintViolation<T> cv : set) {
                log.debug("---{}----",cv.getMessage());
                return ResponseResultUtil.ofError(ExceptionEnum.PARAM_BIND_ERROR.getCode(),cv.getMessage());
            }
        }
        return null;
    }
}
